import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;


public class UdpEchoServer {//服务器
    private DatagramSocket socket=null;//构建socket对象,实现网络通信的必须要求
    public UdpEchoServer(int port) throws SocketException {//在构造方法中初始化客户端,并且绑定端口
        socket=new DatagramSocket(port);//绑定端口,因为是服务器
    }
    //启动服务器的主要逻辑
    public void stack() throws IOException {
        System.out.println("服务器启动");
        while (true){
            DatagramPacket requestPacket=new DatagramPacket(new  byte[4096],4096);//构造空的饭盒,用来接收从客户端发来的数据报
            socket.receive(requestPacket);//填充饭盒
            //为了方便处理请求,把数据报转化为string类型
            String request=new String(requestPacket.getData(),0,requestPacket.getLength());
            //根据请求,服务器做出响应
            String response=process(request);//做出响应
            //把响应结果发送回客户端
            DatagramPacket reaponsePacket=new DatagramPacket(response.getBytes(StandardCharsets.UTF_8),response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(reaponsePacket);
            //打印日志
            System.out.printf("[%s:%d] request:%s,response:%s\n",reaponsePacket.getSocketAddress().toString(),reaponsePacket.getPort(),request,response);
        }
    }

    public String process(String request) {
        return request;//因为是回写程序,所以直接返回原字符串即可
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer udpEchoServer=new UdpEchoServer(4090);//指定服务器端口号
        udpEchoServer.stack();
    }
}
